#include "dvpcam.h"
using namespace std;

Dvpcam::Dvpcam()
{
    dvpInit();
}

Dvpcam::~Dvpcam()
{
    dvpQuit();
}

int Dvpcam::dvpInit()
{
    bool bTrigStatus;
    dvpRefresh(&cam_count);     //刷新相机列表

    if (cam_count == 0)
        cout << "There is no camera linked." << endl;
    else if (cam_count == 1)
        cout << "There is 1 camera linked." << endl;
    else
        cout << "There are " << cam_count << " camera linked." << endl;

    status = dvpOpen(0, OPEN_NORMAL, &m_handle);        //连接相机
    if(status == DVP_STATUS_OK)
        cout << "Open the camera 1 successfully!" << endl;
    else
    {
        cout << "err: Cannot open the device." << endl;
        return 1;
    }

    status = dvpGetTriggerState(m_handle,&bTrigStatus);
    if (status != DVP_STATUS_FUNCTION_INVALID)
    {
        // 在启动视频流之前先设置为触发模式
        status = dvpSetTriggerState(m_handle,SoftTriggerFlag ? true : false);
        if (status != DVP_STATUS_OK)
        {
             QMessageBox::about(NULL,"About","Set status of trigger fail!");
        }
    }
    status = dvpStart(m_handle);        //打开相机视频流

    return 0;
}

int Dvpcam::dvpQuit()
{
    status = dvpStop(m_handle);
    if (status == DVP_STATUS_OK)
        cout << "Stop stream" << endl;
    else
    {
        cout << "ERROR: Stop stream failed" <<endl;
        return -1;
    }
    status = dvpClose(m_handle);
    if (status == DVP_STATUS_OK)
        cout << "Cam closed" << endl;
    else
    {
        cout << "ERROR: Close cam failed" <<endl;
        return -1;
    }

    return 0;
}

int Dvpcam::dvpSave()
{
    bool triggerState;
    QString time;
    QDateTime current_date_time = QDateTime::currentDateTime();
    time = current_date_time.toString("yyyy_MM_dd_hh_mm_ss_zzz");
    QString buf = "/media/nvidia/SD22/"; // /media/root/X/
    buf.append(time);
    buf.append(".jpg");

    status = dvpGetTriggerState(m_handle,&triggerState);
    if (status != DVP_STATUS_FUNCTION_INVALID)
    {
        status = dvpTriggerFire(m_handle);
        if (status != DVP_STATUS_OK)
        {
            QMessageBox::about(NULL,"About","Trigger fail!");
        }
    }

    status = dvpGetFrame(m_handle, &m_pFrame, &pBuffer, m_uGrabTimeout);
    if (status == DVP_STATUS_OK)
    {
        m_ShowImage = QImage((uchar*)pBuffer,m_pFrame.iWidth, m_pFrame.iHeight,m_pFrame.iWidth*3, QImage::Format_RGB888);
        m_ShowImage = m_ShowImage.rgbSwapped();
    }
    if(!m_ShowImage.save(buf,"jpg",-1))
    {
        qDebug("Save image fail!");
        return -1;
    }
    return 0;
}

void Dvpcam::dvpShotSlot()
{
    dvpSave();
    emit dvpokSignal();
}
